package edu.cicese.alz.swing.dialogs;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 26/06/12
 * Time: 05:36 PM
 */
public class CustomDialog extends JDialog {

	private boolean okPressed = false;

	public CustomDialog(JFrame owner, String title, boolean modal) {
		super(owner, title, modal);

		Action actionClose = new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				closeAndDispose();
			}
		};

		InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
		ActionMap actionMap = getRootPane().getActionMap();
		inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
		actionMap.put("close", actionClose);

	}

	public CustomDialog(JFrame owner, String title) {
		super(owner, title);
	}

	public CustomDialog() {
	}

	public void actionOK() {
		setOk(true);
		setVisible(false);
	}

	public void setOk(boolean okPressed) {
		this.okPressed = okPressed;
	}

	public boolean isOk() {
		return okPressed;
	}

	public void closeAndDispose() {
		setVisible(false);
		dispose();
	}

	public void setMin(int minWidth, int minHeight) {
		setPreferredSize(new Dimension(minWidth, minHeight));
		setMinimumSize(getPreferredSize());
	}

	public void setInitialLocation() {
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle window = getBounds();
		setLocation((screen.width - window.width) / 2, (screen.height - window.height) / 2);
	}

	public Icon getIcon(String iconName) {
		return new ImageIcon(getClass().getClassLoader().getResource("icons/" + iconName + ".png"));
	}
}
